package blog

import (
	"github.com/astaxie/beego/orm"
	"github.com/gogf/gf/os/glog"
)

type Classify struct {
	Id         int
	Name       string `orm:"size(16);unique"`
	Key        string `orm:"size(32);unique"`
	ArticleNum int
	Describe   string `orm:"size(64)"`
}

func (m *Classify) TableName() string {
	return "blog_classify"
}

func SetClassifyArticleNum(id int, num int) {
	_, err := orm.NewOrm().QueryTable(new(Classify)).Filter("id", id).Update(orm.Params{"article_num": num})
	if err != nil {
		glog.Errorf("set Classify article num error: %s", err.Error())
	}
}

func GetBlogClassify(id int) (classify Classify, err error) {
	classify = Classify{Id: id}
	err = orm.NewOrm().Read(&classify)
	return
}

func GetBlogClassifyFromKey(key string) (classify Classify, err error) {
	err = orm.NewOrm().QueryTable(new(Classify)).Filter("key", key).One(&classify)
	return
}

func CreateBlogClassify(name, key, describe string) error {
	class := Classify{Name: name, Key: key, Describe: describe}
	_, err := orm.NewOrm().Insert(&class)
	return err
}

func GetAllBlogClassify() (all []*Classify, err error) {
	_, err = orm.NewOrm().QueryTable(new(Classify)).OrderBy("id").All(&all)
	return
}

func GetBlogClassifyPaginator(limit, page int) (all []*Classify, err error) {
	if limit == 0 {
		limit = 10
	}
	if page == 0 {
		page = 1
	}
	_, err = orm.NewOrm().QueryTable(new(Classify)).Offset((page - 1) * limit).Limit(limit).All(&all)
	return
}
